<template>
  <basic-container>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-tabs type="border-card" class="informationLabel">
          <el-tab-pane label="标签生成">
            <avue-form class="newFormStyle dmptyFormButton" key="0" v-model="form" :option="typeOption"></avue-form>
            <avue-form
              v-show="labelPrintType === 'serialnoCreate'"
              :defaults.sync="defaults"
              class="newFormStyle"
              ref="form"
              key="3"
              v-model="model"
              :option="serialnoCreateOption"
              @submit="rawSerialNumberGenerate"
            >
            </avue-form>
            <avue-form
              v-show="labelPrintType === 'serialnoAppend'"
              class="newFormStyle"
              key="4"
              ref="serialnoAppendForm"
              v-model="serialnoAppendForm"
              :option="serialnoAppendOption"
              @submit="serialnoAppendSubmit"
            >
            </avue-form>
            <avue-form
              v-show="labelPrintType === 'packIdCreate'"
              class="newFormStyle"
              ref="packIdCreateForm"
              v-model="packIdCreateForm"
              :option="packIdCreateOption"
              @submit="createPackId"
            >
            </avue-form>
            <avue-form
              v-show="labelPrintType === 'packIdAppend'"
              class="newFormStyle"
              ref="packIdAppendForm"
              v-model="packIdAppendForm"
              :option="packIdAppendOption"
              @submit="appendPackId"
            >
            </avue-form>
          </el-tab-pane>
        </el-tabs>
      </el-col>
      <el-col :span="16">
        <el-tabs type="border-card" class="informationLabel">
          <el-tab-pane label="序列号规则演示">
            <div class="sequenceInfo">
              <table border="1">
                <tr>
                  <th colspan="4">产品序列号规则说明</th>
                </tr>
                <tr>
                  <th>规则名称</th>
                  <th>
                    <el-tooltip class="item" effect="dark" placement="top-start">
                      <i class="el-icon-info" style="color: #606266"></i>
                      <div slot="content">
                        [P]：前缀字符,[YY]：两位年份, [YYYY]：四位年份, [M]：月,<br />[W]：周, [D]：日, [S]：流水号, [N]：自定义字符。<br />[B]：后缀字符 <br />如：[YY][M][S][B]
                        <br />若无流水号则没有[S],例如：[YY][M][B]
                      </div>
                      <!-- <el-button style="padding: 0; font-size: 18px" type="info" icon="el-icon-info" circle></el-button> -->
                    </el-tooltip>
                    序列号规则
                    <el-button
                      v-if="
                        sequenceRuleInfo.sequenceNoFormat &&
                        (sequenceRuleInfo.sequenceNoFormat.indexOf('[YYYY]') > -1 ||
                          sequenceRuleInfo.sequenceNoFormat.indexOf('[YY]') > -1 ||
                          sequenceRuleInfo.sequenceNoFormat.indexOf('[M]') > -1 ||
                          sequenceRuleInfo.sequenceNoFormat.indexOf('[W]') > -1 ||
                          sequenceRuleInfo.sequenceNoFormat.indexOf('[D]') > -1)
                      "
                      style="padding: 5px"
                      type="primary"
                      icon="el-icon-edit"
                      circle
                      @click="openTimeConfigModel"
                    ></el-button>
                  </th>
                  <th>序列号规则位数</th>
                  <th>起始/结束流水（参考）</th>
                </tr>
                <tr style="height: 40px">
                  <td>{{ sequenceRuleInfo.name }}</td>
                  <td>
                    <div>{{ sequenceRuleInfo.sequenceNoFormat }}</div>
                    <div>{{ sequenceRuleInfo.sequenceNoFormatZh }}</div>
                  </td>
                  <td>
                    <div v-if="sequenceRuleInfo.charactersCount">配置长度:{{ sequenceRuleInfo.charactersCount }}</div>
                    <div v-if="sequenceRuleInfo.seqNoFormatDemo">
                      例:{{ sequenceRuleInfo.seqNoFormatDemo }}<span>(当前长度:{{ sequenceRuleInfo.seqNoFormatDemo.length }})</span>
                    </div>
                  </td>
                  <td>
                    {{ startSequenceNo ? startSequenceNo : startSequenceNumber ? startSequenceNumber : '' }}/{{
                      sequenceRuleInfo.endSequenceNo ? sequenceRuleInfo.endSequenceNo : ''
                    }}
                  </td>
                </tr>
              </table>
              <table class="generateSerialNoInfo" border="1">
                <tr>
                  <th colspan="4">产品序列号规则生成示例</th>
                </tr>
                <tr>
                  <th>序列号规则</th>
                  <th>序列号数量</th>
                  <th>起始序列号</th>
                  <th>结尾序列号</th>
                </tr>
                <tr style="height: 40px">
                  <td>[YY][M][S]两位年份[YY]+两位月码[M]+流水[S]</td>
                  <td>10</td>
                  <td>220400001</td>
                  <td>220400010</td>
                </tr>
              </table>
              <el-row>
                <el-col :span="15">
                  <common-printers-template ref="printInfo" :templateType="templateType" @getPrintInfo="getPrintInfo"></common-printers-template>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <el-tabs type="border-card" class="informationLabel">
      <el-tab-pane :label="labelPrintType === 'serialnoCreate' || labelPrintType === 'serialnoAppend' ? '工单序列号生成记录' : '成品包装条码生成记录'">
        <avue-crud
          :defaults.sync="recordDefaults"
          class="serialNoGenerationRecord"
          ref="serialNoGenerationRecord"
          :table-loading="loading"
          :option="serialNoGenerationRecordOption"
          :data="serialnoData"
          @row-click="rowClick"
        >
          <template slot="menuLeft">
            <el-button type="primary" size="small" icon="el-icon-printer" @click="batchPrinting" :disabled="JSON.stringify(selectionInfo) == '{}'">打印</el-button>
          </template>
        </avue-crud>
      </el-tab-pane>
    </el-tabs>
    <!-- 操作日志 -->
    <operation-log ref="operationLog"></operation-log>
    <!-- 选择工单组件 -->
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
    <el-dialog append-to-body title="序列号规则时间修改" :visible.sync="timeConfigModel" width="30%">
      <avue-form ref="timeConfigForm" v-model="timeConfig" :option="timeConfigOption"> </avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="onSaveTimeConfig"> <i class="el-icon-circle-plus-outline"></i><span>保 存</span> </el-button>
        <el-button size="small" @click="timeConfigModel = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>
<script>
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import CommonPrintersTemplate from '@/components/common-printers-template/common-printers-template.vue';
import { getSeqNoRules } from '@/util/global';
import { getYearWeek, focusInput, showSuccessLog, showFailLog, showWarningLog } from '@/util/helpers';
import { getSerialnoCreateOption, getSerialnoAppendOption, getPackIdCreateOption, getPackIdAppendOption } from '@/components/label-manage.js';
import {
  createSequenceByWorkorder,
  sequenceAppend,
  getSourceList,
  sequencePrint,
  getPackingConfigDetail,
  createPackingSequence,
  appendPackingSequence,
  getSequenceGenerationSource,
  packIdPrint,
  sequenceGenerationSum
} from '@/api/product/product-label-create-print';
import { getDetail } from '@/api/admin/sequencedefinition';
import OperationLog from '@/components/operation-log/operation-log.vue';
export default {
  components: {
    CommonModalTemplate,
    CommonPrintersTemplate,
    OperationLog
  },
  data() {
    return {
      labelPrintType: 'serialnoCreate',
      form: {},
      typeOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 130,
        column: [
          {
            label: '类型',
            prop: 'type',
            span: 24,
            type: 'select',
            dicData: [
              { label: '产品序列号', value: '1' },
              { label: '产品序列号增补', value: '2' },
              { label: '成品包装条码', value: '3' },
              { label: '成品包装条码增补', value: '4' }
            ],
            value: '1',
            rules: [
              {
                required: true,
                trigger: 'submit',
                validator: (rule, value, callback) => {
                  callback();
                }
              }
            ],
            change: (val) => {
              this.serialnoData = [];
              this.$refs.form.resetFields();
              this.$refs.serialnoAppendForm.resetFields();
              this.$refs.packIdCreateForm.resetFields();
              this.$refs.packIdAppendForm.resetFields();
              switch (val.value) {
                case '1':
                  this.labelPrintType = 'serialnoCreate';
                  this.recordDefaults.sequenceNumberFrom.label = '起始序列号';
                  this.recordDefaults.sequenceNumberTo.label = '结尾序列号';
                  this.recordDefaults.quantity.label = '序列号总数';
                  this.templateType = 'SN';
                  break;
                case '2':
                  this.labelPrintType = 'serialnoAppend';
                  this.leftCol = '8';
                  this.rightCol = '16';
                  this.recordDefaults.sequenceNumberFrom.label = '起始序列号';
                  this.recordDefaults.sequenceNumberTo.label = '结尾序列号';
                  this.recordDefaults.quantity.label = '序列号总数';
                  this.templateType = 'SN';
                  break;
                case '3':
                  this.labelPrintType = 'packIdCreate';
                  this.recordDefaults.sequenceNumberFrom.label = '起始包装条码';
                  this.recordDefaults.sequenceNumberTo.label = '结尾包装条码';
                  this.recordDefaults.quantity.label = '包装条码总数';
                  this.templateType = 'PRODUCTPACK';
                  break;
                case '4':
                  this.labelPrintType = 'packIdAppend';
                  this.recordDefaults.sequenceNumberFrom.label = '起始包装条码';
                  this.recordDefaults.sequenceNumberTo.label = '结尾包装条码';
                  this.recordDefaults.quantity.label = '包装条码总数';
                  this.templateType = 'PRODUCTPACK';
                  break;
                default:
                  setTimeout(() => {
                    this.$refs.form.resetFields();
                    this.$refs.serialnoAppendForm.resetFields();
                    this.$refs.packIdCreateForm.resetFields();
                    this.$refs.packIdAppendForm.resetFields();
                    for (let key in this.sequenceRuleInfo) {
                      this.$set(this.sequenceRuleInfo, key, '');
                    }
                  });
                  break;
              }
              for (let key in this.sequenceRuleInfo) {
                this.$set(this.sequenceRuleInfo, key, '');
              }
              this.startSequenceNumber = '';
            }
          }
        ]
      },
      model: {}, //序列号生成信息
      serialnoCreateOption: getSerialnoCreateOption(this), //序列号生成信息配置内容
      serialnoAppendForm: {}, //序列号增补表单信息
      serialnoAppendOption: getSerialnoAppendOption(this), //序列号增补表单配置内容
      packIdCreateForm: {},
      packIdCreateOption: getPackIdCreateOption(this), //成品包装条码生成信息配置内容
      packIdAppendForm: {},
      packIdAppendOption: getPackIdAppendOption(this), //成品包装条码增补信息配置内容
      timer: new Date().getTime(),
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      sequenceRuleInfo: {}, //产品序列号规则信息
      recordDefaults: {},
      serialNoGenerationRecordOption: {
        //工单产品序列号内容配置
        height: 300,
        calcHeight: 30,
        border: true,
        index: true,
        viewBtn: false,
        // selection: false,
        dialogClickModal: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        tip: false,
        refreshBtn: false, //刷新按钮是否显示
        columnBtn: false, //控制表格列是否显示按钮是否显示
        menu: false,
        indexLabel: '序号',
        highlightCurrentRow: true,
        column: [
          {
            label: '起始序列号',
            prop: 'sequenceNumberFrom'
          },
          {
            label: '结尾序列号',
            prop: 'sequenceNumberTo'
          },
          {
            label: '序列号总数',
            prop: 'quantity'
          },
          {
            label: '状态',
            prop: 'isPrinted',
            html: true,
            formatter: (val) => {
              switch (val.isPrinted) {
                case 0:
                  return `<span class="text-yellow">未打印</span>`;
                case 1:
                  return `<span class="text-green">已打印</span>`;
                case 2:
                  return `<span class="text-red">部分打印</span>`;
                default:
                  return `<span class="text-red">报废</span>`;
                  break;
              }
            }
          },
          {
            label: '生成时间',
            prop: 'createTime'
          },
          {
            label: '生成类型',
            prop: 'generationType',
            html: true,
            formatter: (val) => {
              switch (val.generationType) {
                case 'NORMAL':
                  return '正常';
                case 'SCRAP':
                  return '报废';
                case 'APPEND':
                  return '增补';
                case 'REPLACE':
                  return '置换';
                default:
                  break;
              }
            }
          }
        ]
      },
      serialnoData: [], //序列号生成记录
      timeConfigModel: false, //序列号规则时间修改模态框是否显示
      timeConfig: {}, //序列号规则时间配置
      timeConfigOption: {
        //序列号规则时间修改内容配置
        labelWidth: 150,
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '年代码',
            prop: 'year',
            type: 'year',
            format: 'yyyy',
            valueFormat: 'yyyy',
            span: 20,
            display: false
          },
          {
            label: '月代码',
            prop: 'month',
            type: 'month',
            format: 'MM',
            valueFormat: 'MM',
            span: 20,
            display: false
          },
          {
            label: '周代码',
            prop: 'week',
            span: 20,
            display: false
          },
          {
            label: '日代码',
            prop: 'day',
            type: 'date',
            format: 'dd',
            valueFormat: 'dd',
            span: 20,
            display: false,
            change(val) {
              console.log(val, Date.parse(val), Object.prototype.toString.call(Date.parse(val)));
            }
          }
        ]
      },
      printInfo: {}, //打印机打印模版信息
      defaults: {},
      selectionInfo: {}, //选中生成记录
      printWorkOrderId: '', //获取工单ID
      getRecordReceivingId: '',
      templateType: '', //需要过滤的标签模版类型
      startSequenceNumber: '', //起始序列号
      startSequenceNo: '' //预生成起始序列号
    };
  },
  mounted() {
    this.timeConfig.year = this.timeConfig.year ? this.timeConfig.year : this.$moment().format('YYYY');
    this.timeConfig.month = this.timeConfig.month ? this.timeConfig.month : this.$moment().format('MM');
    this.timeConfig.week = this.timeConfig.week ? this.timeConfig.week : getYearWeek();
    this.timeConfig.day = this.timeConfig.day ? this.timeConfig.day : this.$moment().format('DD');
  },
  methods: {
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 打开选择工单号模态框
     */
    openWorkorderCommonModal() {
      let url = '/api/mes-product/work-order/page';
      let status = [
        {
          label: '待排程',
          value: 1
        },
        {
          label: '待生产',
          value: 2
        },
        {
          label: '生产中',
          value: 3
        },
        {
          label: '完工',
          value: 4
        },
        {
          label: '锁定',
          value: 5
        },
        {
          label: '强制完工',
          value: 6
        }
      ];
      if (this.form.type === '1' || this.form.type === '2') {
        url = '/api/mes-product/work-order/page?workOrderStatus=2,3';
        status = [
          {
            label: '已派工',
            value: 2
          },
          {
            label: '生产中',
            value: 3
          }
        ];
      }
      this.modalName = 'workorderModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择工单号（双击进行选择）',
        url: url,
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '生产订单',
            prop: 'productionOrderNo',
            search: true,
            searchType: 'input',
            type: 'search'
          },
          {
            label: '生产工单',
            prop: 'orderNo',
            search: true
          },
          {
            label: '工单类型',
            prop: 'orderType',
            type: 'select',
            rules: [
              {
                required: true,
                message: '请选择工单类型',
                trigger: 'change'
              }
            ],
            dicUrl: '/api/blade-system/dict/dictionary?code=order_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '工单数量',
            prop: 'planQuantity',
            type: 'number',
            minRows: 1
          },
          {
            label: '产品编码',
            prop: 'partNo',
            search: true,
            searchType: 'input',
            type: 'search'
          },
          {
            label: '产品名称',
            prop: 'partName',
            search: true
          },
          {
            label: 'BOM版本',
            prop: 'bomVersion',
            type: 'search'
          },
          {
            label: '派工产线',
            prop: 'productionLineName',
            search: true,
            searchType: 'input',
            type: 'search'
          },
          {
            label: '计划开始时间',
            prop: 'planStartDate',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            label: '计划结束时间',
            prop: 'planEndDate',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            label: '制定人',
            prop: 'creatorName',
            disabled: true
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            search: true,
            dicData: status
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea'
          }
        ]
      };
    },
    /**
     * 获取选择的模态框行数据
     */
    getSelectedRows(rowData) {
      if (this.modalName === 'workorderModal') {
        this.printWorkOrderId = this._get(rowData, 'id', '');
        switch (this.labelPrintType) {
          case 'serialnoCreate':
            this.model.workOrderId = this._get(rowData, 'id', '');
            this.model.workOrderNo = this._get(rowData, 'orderNo', '');
            this.model.partNo = this._get(rowData, 'partNo', '');
            this.model.partName = this._get(rowData, 'partName', '');
            this.model.partModel = this._get(rowData, 'partModel', '');
            this.model.sequenceDefinitionId = this._get(rowData, 'productSequenceDefinitionId', '');
            this.model.sequenceName = this._get(rowData, 'sequenceDefinitionName', '');
            this.model.quantity = this._get(rowData, 'planQuantity', '');
            this.printInfo.labelTemplateId = this._get(rowData, 'labelTemplateId', '');
            this.$refs.printInfo.model.labelTemplateName = this._get(rowData, 'labelTemplateName', '');
            if (this.model.sequenceDefinitionId) {
              this.getSequencedefinitionDetail(this.model.sequenceDefinitionId);
              this.getStartOrEndSequenceNumber(this.model.sequenceDefinitionId);
            }
            this.getSequenceRecordById(this._get(rowData, 'id', ''), 'PRODUCT_WORK_ORDER');
            break;
          case 'serialnoAppend':
            this.serialnoAppendForm.workOrderId = this._get(rowData, 'id', '');
            this.serialnoAppendForm.workOrderNo = this._get(rowData, 'orderNo', '');
            this.serialnoAppendForm.partNo = this._get(rowData, 'partNo', '');
            this.serialnoAppendForm.partName = this._get(rowData, 'partName', '');
            this.serialnoAppendForm.partModel = this._get(rowData, 'partModel', '');
            this.serialnoAppendForm.sequenceDefinitionId = this._get(rowData, 'productSequenceDefinitionId', '');
            this.serialnoAppendForm.sequenceName = this._get(rowData, 'sequenceDefinitionName', '');
            this.serialnoAppendForm.quantity = this._get(rowData, 'planQuantity', '');
            this.printInfo.labelTemplateId = this._get(rowData, 'labelTemplateId', '');
            this.$refs.printInfo.model.labelTemplateName = this._get(rowData, 'labelTemplateName', '');
            if (this.serialnoAppendForm.sequenceDefinitionId) {
              this.getSequencedefinitionDetail(this.serialnoAppendForm.sequenceDefinitionId);
              this.getStartOrEndSequenceNumber(this.serialnoAppendForm.sequenceDefinitionId);
            }
            this.getSequenceRecordById(this._get(rowData, 'id', ''), 'PRODUCT_WORK_ORDER');
            break;
          case 'packIdCreate':
            this.packIdCreateForm.workOrderId = this._get(rowData, 'id', '');
            this.packIdCreateForm.workOrderNo = this._get(rowData, 'orderNo', '');
            this.packIdCreateForm.partNo = this._get(rowData, 'partNo', '');
            this.packIdCreateForm.partName = this._get(rowData, 'partName', '');
            this.packIdCreateForm.partModel = this._get(rowData, 'partModel', '');
            this.packIdCreateForm.quantity = this._get(rowData, 'planQuantity', '');
            this.packIdCreateForm.productPackingConfigId = this._get(rowData, 'productPackingConfigId', '');
            this.printInfo.labelTemplateId = this._get(rowData, 'labelTemplateId', '');
            this.$refs.printInfo.model.labelTemplateName = this._get(rowData, 'labelTemplateName', '');
            if (this.packIdCreateForm.productPackingConfigId && this.packIdCreateForm.productPackingConfigId != null) {
              this.getPackingConfig();
            } else {
              this.packIdCreateForm.packingConfigDetailId = '';
              this.packIdCreateOption.column[5].dicData = [];
              this.$message({
                type: 'warning',
                message: '请在工单工艺路线中选择包装配置！'
              });
            }
            break;
          case 'packIdAppend':
            this.packIdAppendForm.workOrderId = this._get(rowData, 'id', '');
            this.packIdAppendForm.workOrderNo = this._get(rowData, 'orderNo', '');
            this.packIdAppendForm.partNo = this._get(rowData, 'partNo', '');
            this.packIdAppendForm.partName = this._get(rowData, 'partName', '');
            this.packIdAppendForm.partModel = this._get(rowData, 'partModel', '');
            this.packIdAppendForm.quantity = this._get(rowData, 'planQuantity', '');
            this.packIdAppendForm.productPackingConfigId = this._get(rowData, 'productPackingConfigId', '');
            this.printInfo.labelTemplateId = this._get(rowData, 'labelTemplateId', '');
            this.$refs.printInfo.model.labelTemplateName = this._get(rowData, 'labelTemplateName', '');
            if (this.packIdAppendForm.productPackingConfigId && this.packIdAppendForm.productPackingConfigId != null) {
              this.getPackingConfig();
            } else {
              this.packIdAppendForm.packingConfigDetailId = '';
              this.packIdAppendOption.column[5].dicData = [];
              this.$message({
                type: 'warning',
                message: '请在工单工艺路线中选择包装配置！'
              });
            }
            break;
          default:
            break;
        }
      } else if (this.modalName === 'serialnoModal') {
        switch (this.labelPrintType) {
          case 'serialnoCreate':
            this.model.sequenceDefinitionId = this._get(rowData, 'id', '');
            this.model.sequenceName = this._get(rowData, 'name', '');
            this.getStartOrEndSequenceNumber(this.model.sequenceDefinitionId);
            break;
          case 'serialnoAppend':
            this.serialnoAppendForm.sequenceDefinitionId = this._get(rowData, 'id', '');
            this.serialnoAppendForm.sequenceName = this._get(rowData, 'name', '');
            this.getStartOrEndSequenceNumber(this.serialnoAppendForm.sequenceDefinitionId);
            break;
          case 'packIdCreate':
            this.packIdCreateForm.sequenceDefinitionId = this._get(rowData, 'id', '');
            this.packIdCreateForm.sequenceName = this._get(rowData, 'name', '');
            this.getStartOrEndSequenceNumber(this.packIdCreateForm.sequenceDefinitionId);
            break;
          case 'packIdAppend':
            this.packIdAppendForm.sequenceDefinitionId = this._get(rowData, 'id', '');
            this.packIdAppendForm.sequenceName = this._get(rowData, 'name', '');
            this.getStartOrEndSequenceNumber(this.packIdAppendForm.sequenceDefinitionId);
            break;
          default:
            break;
        }
        this.sequenceRuleInfo.id = this._get(rowData, 'id', '');
        this.getSequencedefinitionDetail(this.sequenceRuleInfo.id);
        this.seqNoConvert();
      }
    },
    /**
     * 根据序列号规则ID查询详情
     */
    getSequencedefinitionDetail(sequencedefinitionId) {
      getDetail(sequencedefinitionId).then((res) => {
        this.$set(this.sequenceRuleInfo, 'name', this._get(res, 'data.data.name', ''));
        this.$set(this.sequenceRuleInfo, 'sequenceNoFormat', this._get(res, 'data.data.sequenceNoFormat', ''));
        this.$set(this.sequenceRuleInfo, 'sequenceNoFormatZh', this._get(res, 'data.data.sequenceNoFormatZh', ''));
        this.$set(this.sequenceRuleInfo, 'seqNoFormatDemo', this._get(res, 'data.data.seqNoFormatDemo', ''));
        this.$set(this.sequenceRuleInfo, 'containsSequenceNo', this._get(res, 'data.data.containsSequenceNo', true));
        this.$set(this.sequenceRuleInfo, 'charactersCount', this._get(res, 'data.data.charactersCount', 0));
        let isPregenerated = this._get(res, 'data.data.isPregenerated', '');
        if (isPregenerated) {
          this.startSequenceNo = this._get(res, 'data.data.used', '');
          this.$set(this.sequenceRuleInfo, 'endSequenceNo', this._get(res, 'data.data.total', ''));
        } else {
          this.startSequenceNo = '';
          this.$set(this.sequenceRuleInfo, 'endSequenceNo', this._get(res, 'data.data.endSequenceNo', ''));
        }
        this.seqNoConvert();
      });
    },
    /**
     * 获取包装层级
     */
    getPackingConfig() {
      if (this.labelPrintType === 'packIdCreate') {
        getPackingConfigDetail(this.packIdCreateForm.productPackingConfigId).then(
          (res) => {
            this.packIdCreateOption.column[5].dicData = this._get(res, 'data.data', []);
          },
          (error) => {
            this.packIdCreateOption.column[5].dicData = [];
          }
        );
      } else {
        getPackingConfigDetail(this.packIdAppendForm.productPackingConfigId).then(
          (res) => {
            this.packIdAppendOption.column[5].dicData = this._get(res, 'data.data', []);
          },
          (error) => {
            this.packIdAppendOption.column[5].dicData = [];
          }
        );
      }
    },
    /**
     * 打开序列号规则选择模态框
     */
    openSerialnoCommonModal() {
      this.modalName = 'serialnoModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择序列号规则（双击进行选择）',
        url: '/api/mes-admin/sequencedefinition/page?type=material&sub_type=work_in_progress',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '序列号规则名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '序列号规则编码',
            prop: 'code',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '进制符',
            prop: 'hexString'
          },
          {
            label: '起始流水号',
            prop: 'startSequenceNo'
          },
          {
            label: '序列号规则',
            prop: 'sequenceNoFormat'
          }
        ]
      };
    },
    /**
     * 序列号规则转换中文
     * @param sequenceNoValue 序列号规则
     * @param sequenceNo 序列号规则起始流水号
     */
    seqNoConvert() {
      let seqNoRules = [];
      this._forEach(getSeqNoRules(), (item) => {
        seqNoRules = [...seqNoRules, ...item.value];
      });
      let splitList = this.sequenceRuleInfo.sequenceNoFormat.split('');
      //在[前加空格  ]后加空格
      splitList = splitList.map((item) => {
        if (item === '[') {
          return ' [';
        } else if (item === ']') {
          return '] ';
        } else {
          return item;
        }
      });
      splitList = splitList.join('');
      //按空格拆分字符串
      splitList = splitList.split(' ');
      //匹配中文
      console.log(splitList);
      console.log(seqNoRules);
      let splitArr = this._map(splitList, (item) => {
        this._forEach(seqNoRules, (ele) => {
          if (item === ele.key) {
            item = ele.value;
          }
        });
        return item;
      });
      //去除空格
      splitArr = splitArr.filter(function (s) {
        return s && s.trim();
      });
      //转换后给序列号规则赋值
      this.sequenceRuleInfo.sequenceNoFormatZh = splitArr.join('+');

      let splitDemoArr = this._map(splitList, (item) => {
        this._forEach(seqNoRules, (ele) => {
          if (item === ele.key) {
            let currentDate = new Date();
            switch (item) {
              case '[YY]':
                let year = String(currentDate.getFullYear());
                item = year.substring(2, year.length);
                break;
              case '[YYYY]':
                item = currentDate.getFullYear();
                break;
              case '[M]':
                let month = currentDate.getMonth() + 1;
                if (month < 10) {
                  item = '0' + month;
                } else {
                  item = month;
                }
                break;
              case '[W]':
                let today = new Date();
                let firstDay = new Date(today.getFullYear(), 0, 1);
                let dayOfWeek = firstDay.getDay();
                let spendDay = 1;
                if (dayOfWeek != 0) {
                  spendDay = 7 - dayOfWeek + 1;
                }
                firstDay = new Date(today.getFullYear(), 0, 1 + spendDay);
                let d = Math.ceil((today.valueOf() - firstDay.valueOf()) / 86400000);
                let week = Math.ceil(d / 7);
                week = week + 1;
                if (week < 10) {
                  item = '0' + week;
                } else {
                  item = week;
                }
                break;
              case '[D]':
                let day = currentDate.getDate();
                if (day < 10) {
                  item = '0' + day;
                } else {
                  item = day;
                }
                break;
              case '[S]':
                if (this.sequenceRuleInfo.sequenceNo) {
                  item = this.sequenceRuleInfo.sequenceNo;
                } else {
                  item = this.sequenceRuleInfo[ele.code];
                }
                break;
              case '[WO]':
                if (this.model.workOrderNo) {
                  item = this.model.workOrderNo;
                } else {
                  item = '[WO]';
                }
                break;
              default:
                if (ele.code) {
                  item = this.sequenceRuleInfo[ele.code];
                }
                break;
            }
          }
        });
        return item;
      });
      splitDemoArr = splitDemoArr.filter(function (item) {
        return String(item) && String(item).trim();
      });
      this.sequenceRuleInfo.seqNoFormatDemo = splitDemoArr.join('');
    },
    /**
     * 序列号规则时间修改
     */
    openTimeConfigModel() {
      this.timeConfigModel = true;
      this.timeConfig.year = this.timeConfig.year ? this.timeConfig.year : this.$moment().format('YYYY');
      this.timeConfig.month = this.timeConfig.month ? this.timeConfig.month : this.$moment().format('MM');
      this.timeConfig.week = this.timeConfig.week ? this.timeConfig.week : getYearWeek();
      this.timeConfig.day = this.timeConfig.day ? this.timeConfig.day : this.$moment().format('DD');
      this.$nextTick(() => {
        let column = this.$refs.timeConfigForm.option.column;
        if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[YYYY]') > -1 || this.sequenceRuleInfo.sequenceNoFormat.indexOf('[YY]') > -1) {
          let year = this.findObject(column, 'year');
          year.display = true;
        }
        if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[M]') > -1) {
          let month = this.findObject(column, 'month');
          month.display = true;
        }
        if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[W]') > -1) {
          let week = this.findObject(column, 'week');
          week.display = true;
        }
        if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[W]') > -1) {
          let week = this.findObject(column, 'week');
          week.display = true;
        }
        if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[D]') > -1) {
          let day = this.findObject(column, 'day');
          day.display = true;
        }
      });
    },
    /**
     * 序列号规则中时间修改保存
     */
    onSaveTimeConfig() {
      //验证是否传递序列号规则中年份日期
      if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[YYYY]') > -1 || this.sequenceRuleInfo.sequenceNoFormat.indexOf('[YY]') > -1) {
        if (!this.timeConfig.year) {
          this.$message({
            type: 'error',
            message: '请选择序列号规则中的年份！'
          });
          return;
        }
      }
      if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[M]') > -1) {
        if (!this.timeConfig.month) {
          this.$message({
            type: 'error',
            message: '请选择序列号规则中的月份！'
          });
          return;
        }
      }
      if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[W]') > -1) {
        if (!this.timeConfig.week) {
          this.$message({
            type: 'error',
            message: '请输入序列号规则中的周数！'
          });
          // Helpers.selectInput('week');
          return;
        }
      }
      if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[D]') > -1) {
        if (!this.timeConfig.day) {
          this.$message({
            type: 'error',
            message: '请选择序列号规则中的日期！'
          });
          return;
        }
      }
      this.timeConfigModel = false;
    },
    /**
     * 产品序列号生成
     */
    rawSerialNumberGenerate(row, done) {
      if (!this.form.type) {
        this.$message({
          type: 'warning',
          message: '请选择类型!'
        });
        done();
        return;
      }
      if (!row.workOrderNo) {
        this.$message({
          type: 'warning',
          message: '请选择工单号!'
        });
        done();
        return;
      }
      if (!row.sequenceName) {
        this.$message({
          type: 'warning',
          message: '请选择序列号规则!'
        });
        done();
        return;
      }
      if (!row.produceQuantity) {
        this.$message({
          type: 'warning',
          message: '请输入生成数量!'
        });
        done();
        return;
      }
      let reg = /^[1-9]\d*$/g;
      if (!reg.test(row.produceQuantity)) {
        this.$message({
          type: 'warning',
          message: '生成数量为正整数!'
        });
        done();
        return;
      }
      let attr = {
        workOrderId: this.model.workOrderId,
        quantity: row.produceQuantity,
        sequenceDefinitionId: this.model.sequenceDefinitionId,
        timeConfig: this.timeConfig
      };

      createSequenceByWorkorder(attr).then(
        (res) => {
          if (res.data.data.options && res.data.data.options != null) {
            let options = JSON.parse(res.data.data.options);
            if (options.isWarning) {
              this.$message({
                type: 'warning',
                message: `${res.data.msg}，可用码段不足${options.warningQuantity}，剩余${options.availableQuantity}，请联系相关人员购买！`
              });
              showWarningLog(`${res.data.msg}，可用码段不足${options.warningQuantity}，剩余${options.availableQuantity}，请联系相关人员购买！`);
            } else {
              this.$message({
                type: 'success',
                message: res.data.msg
              });
              showSuccessLog(res.data.msg);
            }
          }
          this.getSequenceRecordById(this.model.workOrderId, 'PRODUCT_WORK_ORDER');
          this.getStartOrEndSequenceNumber(this.model.sequenceDefinitionId);
          done();
        },
        (error) => {
          showFailLog(error.data.msg);
          done();
        }
      );
    },

    /**
     * 序列号增补
     */
    serialnoAppendSubmit(row, done) {
      if (!this.form.type) {
        this.$message({
          type: 'warning',
          message: '请选择类型!'
        });
        done();
        return;
      }
      if (!row.workOrderNo) {
        this.$message({
          type: 'warning',
          message: '请选择工单号!'
        });
        done();
        return;
      }
      if (!row.sequenceName) {
        this.$message({
          type: 'warning',
          message: '请选择序列号规则!'
        });
        done();
        return;
      }
      if (!row.produceQuantity) {
        this.$message({
          type: 'warning',
          message: '请输入序列号数量!'
        });
        done();
        return;
      }
      let reg = /^[1-9]\d*$/g;
      if (!reg.test(row.produceQuantity)) {
        this.$message({
          type: 'warning',
          message: '序列号数量为正整数!'
        });
        done();
        return;
      }
      if (!row.remark) {
        this.$message({
          type: 'warning',
          message: '请输入原因说明!'
        });
        done();
        return;
      }
      let params = {
        workOrderId: this.serialnoAppendForm.workOrderId,
        sequenceDefinitionId: this.serialnoAppendForm.sequenceDefinitionId,
        quantity: this.serialnoAppendForm.produceQuantity,
        remark: this.serialnoAppendForm.remark,
        timeConfig: this.timeConfig
      };
      sequenceAppend(params).then(
        (res) => {
          if (res.data.data.options && res.data.data.options != null) {
            let options = JSON.parse(res.data.data.options);
            if (options.isWarning) {
              this.$message({
                type: 'warning',
                message: `${res.data.msg}，可用码段不足${options.warningQuantity}，剩余${options.availableQuantity}，请联系相关人员购买！`
              });
              showWarningLog(`${res.data.msg}，可用码段不足${options.warningQuantity}，剩余${options.availableQuantity}，请联系相关人员购买！`);
            } else {
              this.$message({
                type: 'success',
                message: res.data.msg
              });
              showSuccessLog(res.data.msg);
            }
          }
          this.getSequenceRecordById(this.serialnoAppendForm.workOrderId, 'PRODUCT_WORK_ORDER');
          this.getStartOrEndSequenceNumber(this.serialnoAppendForm.sequenceDefinitionId);
          done();
        },
        (error) => {
          showFailLog(error.data.msg);
          done();
        }
      );
    },
    /**
     * 生成包装条码
     */
    createPackId(row, done) {
      if (!row.workOrderNo) {
        this.$message({
          type: 'warning',
          message: '请选择工单号!'
        });
        done();
        return;
      }
      if (!row.packingConfigDetailId) {
        this.$message({
          type: 'warning',
          message: '请选择包装层级!'
        });
        done();
        return;
      }
      if (!row.createQuantity) {
        this.$message({
          type: 'warning',
          message: '请输入生成数量!'
        });
        done();
        return;
      }
      let reg = /^[1-9]\d*$/g;
      if (!reg.test(row.createQuantity)) {
        this.$message({
          type: 'warning',
          message: '生成数量为正整数!'
        });
        done();
        return;
      }
      let params = {
        workOrderId: this.packIdCreateForm.workOrderId,
        productPackingDetailId: this.packIdCreateForm.packingConfigDetailId,
        sequenceDefinitionId: this.packIdCreateForm.sequenceDefinitionId,
        mpq: this.packIdCreateForm.mpq,
        quantity: this.packIdCreateForm.createQuantity,
        timeConfig: this.timeConfig
      };
      createPackingSequence(params).then(
        (res) => {
          this.packIdCreateForm.createQuantity = '';
          this.getPackingSequenceRecord();
          this.getStartOrEndSequenceNumber(this.packIdCreateForm.sequenceDefinitionId);
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          showSuccessLog(res.data.msg);
          done();
        },
        (error) => {
          showFailLog(error.data.msg);
          done();
        }
      );
    },
    /**
     * 增补包装条码
     */
    appendPackId(row, done) {
      if (!row.workOrderNo) {
        this.$message({
          type: 'warning',
          message: '请选择工单号!'
        });
        done();
        return;
      }
      if (!row.packingConfigDetailId) {
        this.$message({
          type: 'warning',
          message: '请选择包装层级!'
        });
        done();
        return;
      }
      if (!row.createQuantity) {
        this.$message({
          type: 'warning',
          message: '请输入生成数量!'
        });
        done();
        return;
      }
      let reg = /^[1-9]\d*$/g;
      if (!reg.test(row.createQuantity)) {
        this.$message({
          type: 'warning',
          message: '生成数量为正整数!'
        });
        done();
        return;
      }
      let params = {
        workOrderId: this.packIdAppendForm.workOrderId,
        productPackingDetailId: this.packIdAppendForm.packingConfigDetailId,
        sequenceDefinitionId: this.packIdAppendForm.sequenceDefinitionId,
        mpq: this.packIdAppendForm.mpq,
        quantity: this.packIdAppendForm.createQuantity,
        description: this.packIdAppendForm.description,
        timeConfig: this.timeConfig
      };
      appendPackingSequence(params).then(
        (res) => {
          this.packIdCreateForm.createQuantity = '';
          this.packIdAppendForm.description = '';
          this.getPackingSequenceRecord();
          this.getStartOrEndSequenceNumber(this.packIdAppendForm.sequenceDefinitionId);
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          showSuccessLog(res.data.msg);
          done();
        },
        (error) => {
          showFailLog(error.data.msg);
          done();
        }
      );
    },
    /**
     * 根据id获取产品序列号生成记录
     */
    getSequenceRecordById(id, type) {
      let params = {
        sourceId: id,
        sourceType: type
      };
      getSourceList(params).then(
        (res) => {
          this.serialnoData = this._get(res, 'data.data', []);
          this.model.total = 0;
          this.serialnoAppendForm.total = 0;
          this._forEach(this.serialnoData, (item) => {
            if (this.labelPrintType === 'serialnoCreate') {
              this.model.total = Number(this.model.total) + Number(item.quantity);
            } else if (this.labelPrintType === 'serialnoAppend') {
              this.serialnoAppendForm.total = Number(this.serialnoAppendForm.total) + Number(item.quantity);
            }
          });
        },
        (error) => {
          this.model.total = 0;
          this.serialnoAppendForm.total = 0;
          this.serialnoData = [];
        }
      );
    },
    /**
     * 获取生成包装条码记录
     */
    getPackingSequenceRecord() {
      let params;
      if (this.labelPrintType === 'packIdCreate') {
        params = {
          sourceId: this.packIdCreateForm.workOrderId,
          productPackingDetailId: this.packIdCreateForm.packingConfigDetailId
        };
      } else if (this.labelPrintType === 'packIdAppend') {
        params = {
          sourceId: this.packIdAppendForm.workOrderId,
          productPackingDetailId: this.packIdAppendForm.packingConfigDetailId
        };
      }
      getSequenceGenerationSource(params).then(
        (res) => {
          this.serialnoData = this._get(res, 'data.data', []);
          // let generatedQuantity = 0;
          // this._forEach(this.serialnoData, (item) => {
          //     generatedQuantity = generatedQuantity + item.quantity;
          // });
          // this.model.surplusQuantity = this.model.quantity - generatedQuantity;
        },
        (error) => {
          this.serialnoData = [];
        }
      );
    },
    /**
     * 表格选中列表
     */
    rowClick(row) {
      this.selectionInfo = row;
      this.$refs.serialNoGenerationRecord.setCurrentRow(row);
    },
    /**
     * 获取打印机和打印模版信息
     */
    getPrintInfo(printInfo) {
      if (printInfo.printersId) {
        this.printInfo.printersId = printInfo.printersId;
      }
      if (printInfo.labelTemplateId) {
        this.printInfo.labelTemplateId = printInfo.labelTemplateId;
      }
    },
    /**
     * 标签打印
     */
    batchPrinting() {
      if (!this.printInfo.printersId) {
        this.$message({
          type: 'warning',
          message: '请选择打印机！'
        });
        return;
      }
      if (!this.printInfo.labelTemplateId) {
        this.$message({
          type: 'warning',
          message: '请选择标签模版！'
        });
        return;
      }
      let params = {
        equipmentId: this.printInfo.printersId,
        labelTemplateId: this.printInfo.labelTemplateId,
        sequenceGenerationId: this._get(this.selectionInfo, 'id', '')
      };
      if (this.labelPrintType === 'serialnoCreate' || this.labelPrintType === 'serialnoAppend') {
        params.workOrderId = this.printWorkOrderId;
        sequencePrint(params).then(
          (res) => {
            this.$message({
              type: 'success',
              message: res.data.msg
            });
            showSuccessLog(res.data.msg);
            this.getSequenceRecordById(this.printWorkOrderId, 'PRODUCT_WORK_ORDER');
          },
          (error) => {
            showFailLog(res.data.msg);
          }
        );
      } else {
        packIdPrint(params).then(
          (res) => {
            this.$message({
              type: 'success',
              message: res.data.msg
            });
            showSuccessLog(res.data.msg);
            this.getPackingSequenceRecord();
          },
          (error) => {
            showFailLog(res.data.msg);
          }
        );
      }
    },
    getStartOrEndSequenceNumber(sequenceDefinitionId) {
      let params = {
        sourceId: this.printWorkOrderId,
        sequenceDefinitionId: sequenceDefinitionId
      };
      sequenceGenerationSum(params).then(
        (res) => {
          this.startSequenceNumber = this._get(res, 'data.data', '');
        },
        (error) => {
          this.startSequenceNumber = '';
        }
      );
    }
  }
};
</script>
<style lang="scss" scoped>
.sequenceInfo {
  table {
    width: 100%;
    height: auto;
    margin-bottom: 10px;
    font-size: 14px;
    th {
      border: 1px solid #ebeef5;
      background: #fafafa;
      height: 30px;
    }
    tr {
      border: 1px solid #ebeef5;
    }
    td {
      border: 1px solid #ebeef5;
      height: auto;
      text-align: center;
    }
    p {
      margin-left: 30px;
    }
  }
}
.newFormStyle {
  ::v-deep .el-form-item--small.el-form-item {
    margin-bottom: 5px;
  }
  ::v-deep .el-input--small input {
    height: 30px;
    line-height: 30px;
  }
}
.generateSerialNoInfo {
  div {
    margin: 5px 10px;
  }
}
.printButton {
  text-align: right;
}
</style>
